﻿using qqdest.Model;
using qqdest.Service;
using qqdest.ServiceImpl;
using qqdest.VC;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace qqdest
{
    public partial class FrmLogin : Form
    {
        // Service 接口
        IUserService userService {  get; set; }

        public FrmLogin()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }


        private void FrmLogin_Load(object sender, EventArgs e)
        {
            // 项目启动时候登录按钮暂时不能使用
            this.btnLogin.Enabled = false;

            // 手动指定当前  View 使用到的 Service
            this.userService = new UserServuceImpl();
        }

        private void txUser_TextChanged(object sender, EventArgs e)
        {
            if (userService.CheckUserInput(this.txUser.Text.Trim(), 6) && userService.CheckUserInput(this.txPwd.Text.Trim(), 6))
            {
                this.btnLogin.Enabled = true;
                return;
            }
            this.btnLogin.Enabled = false;
        }

        private void txPwd_TextChanged(object sender, EventArgs e)
        {
            if (userService.CheckUserInput(this.txUser.Text.Trim(), 6) && userService.CheckUserInput(this.txPwd.Text.Trim(), 6)) 
            {
                this.btnLogin.Enabled = true;
                return;
            }
            this.btnLogin.Enabled = false;
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // 封装实体类
            User user = new User(this.txUser.Text.Trim(), this.txPwd.Text.Trim());
            if (userService.Login(user))
            {
                MessageBox.Show("登录成功");
                // 登录成功, 修改 Dialog 的返回值为 OK， Close 此登录模态框
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("登录失败");
                // 登录失败, 则清楚密码框
                this.txPwd.Clear();
            }
        }   

        private void btnRegister_Click(object sender, EventArgs e)
        {
            FrmRegister frmRegister = new FrmRegister();
            this.Hide();
            frmRegister.FormClosed += Frm_FormClosed;  // 窗体关闭事件绑定，当注册窗口关闭的时候， 靠事件去显示登录模态框
            
            // 当注册成功的时候, 注册窗口显示登录成功按钮
            if (frmRegister.ShowDialog() == DialogResult.OK)
            {
                this.Show();
            }
        }

        private void Frm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Show();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
